package cn.trigram.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
@Setter(onMethod_ = {@Autowired})
public class NacosWeightRule extends AbstractLoadBalancerRule {

  private NacosDiscoveryProperties nacosDiscoveryProperties;

  private NacosServiceManager nacosServiceManager;

  @Override
  public void initWithNiwsConfig(IClientConfig clientConfig) {

  }

  /**
   * @param key 默认值是default
   */
  @Override
  public Server choose(Object key) {

    try {
      BaseLoadBalancer loadBalancer = (BaseLoadBalancer)this.getLoadBalancer();
      String           name         = loadBalancer.getName();
      NamingService namingService = nacosServiceManager.getNamingService(
          nacosDiscoveryProperties.getNacosProperties());
      Instance instance = namingService.selectOneHealthyInstance(name);
      log.debug("根据权重选中的server:{}", instance);
      return new NacosServer(instance);
    } catch (NacosException e) {
      e.printStackTrace();
    }
    return null;
  }

}
